import React from 'react'
import {
    Button,
    message,
    Modal
} from 'antd'
import ModelTransfer from "components/modelTransfer"
import Table from 'components/table'
import {
    FormModal
} from 'components/modalForm'
import 'whatwg-fetch'
import './index.less'

import axios from "axios";

require('es6-promise').polyfill();
axios.interceptors.request.use(function (config) {    // 这里的config包含每次请求的内容
    var type = sessionStorage.getItem("user_token");
   config.headers.user_token = type;

    return config;
}, function (err) {
    return Promise.reject(err);
});


const confirm = Modal.confirm
/*let arr=[{
    value: 2,
    mean: '上海',
},
    {
        value: 1,
        mean: '北京',
    }]*/
export default class Music extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            dataSource:[],
            targetSource:[],
            tData: [],
            item: {},
            targetKeys:[],
            loading: true,
            modalShow: false,
            modalShowEdit: false,
            modalShowSet:false,
            total:0,
            current:1,
            pageSize:10,
            rowId:""
        }
        this.add = this.add.bind(this)
        this.onOk = this.onOk.bind(this)
        this.onCancel = this.onCancel.bind(this)
        this.onOkEdit = this.onOkEdit.bind(this)
        this.onCancelEdit = this.onCancelEdit.bind(this)
        this.changePage = this.changePage.bind(this)
        this.onCancelSet= this.onCancelSet.bind(this)
        this.onOkSet = this.onOkSet.bind(this)
    }

    // 获取表格数据
    fetchTableData = (n) => {

        axios.get(`/auth/users?pageNum=${n}&pageSize=10`).then((res)=>{

            const  userArray =[];
            let userList =  res.data.list;

            for (let i = 0; i < userList.length; i++) {
                userArray.push({
                    realname: userList[i].realname,
                    createdAt: userList[i].createdAt,
                    username:userList[i].username,
                    description:userList[i].description,
                    roles:userList[i].roles,
                    id:userList[i].id,
                    enabled:userList[i].enabled
                })
            }

            this.setState({
                tData: userArray,
                total:res.data.total,
                loading: false,
                current:n
            });

        })

    }

    componentDidMount() {
        this.fetchTableData(1) // 默认
    }



    tableHeader = () => {
        return [{
            dataIndex: 'realname',
            title: '用户名',
            width: 200,
            // render: (text, record) => {
            // }
        }, {
            dataIndex: 'createdAt',
            title: '创建时间',
            width: 200,
        }
            , {
                dataIndex: 'username',
                title: '账号',
                width: 200,
            }
            , {
                dataIndex: 'description',
                title: '描述',
                width: 200,
            }
            , {
                dataIndex: 'roles',
                title: '关联',
                width: 200,
            }]
    }
    changePage(n){


        this.fetchTableData(n);
    }
    add() {
        this.setState({
            modalShow: true
        })
    }

    onOk(param) {

        axios.post("/auth/users",{
            realname:param.realname,
            username:param.username,
            description:param.description,

        }).then( (res)=>{
            if(res.status === 200){
                message.success('添加成功');
                this.onCancel();
                this.fetchTableData(1);
            }


        })

    }

    onCancel() {
        this.setState({
            modalShow: false
        })
    }
  onCancelSet(){
        this.setState({
            modalShowSet: false
        })
    }
  onOkSet(param){

     let roleId = param;
     let itemId =this.state.rowId;
     axios.post(`/auth/users/${itemId}/roles`,{
            "roleIds":roleId
        }).then((res)=>{

        })
    }
    onCanCel=(param)=>{
        let roleId = param;
        let itemId =this.state.rowId;

        axios.delete(`/auth/users/${itemId}/roles`,{
            "roleIds":roleId
        }).then((res)=>{

        })
    }
    onOkEdit(param) {
        this.setState({
            modalShowEdit: false
        });
       axios.put("/auth/users/"+param.id,{
           realname:param.realname,
           description:param.description
        }).then(()=>{
           this.fetchTableData(1);
           message.success('编辑成功');
       })

    }

    onCancelEdit() {
        this.setState({
            modalShowEdit: false
        })
    }

    tableAction = (actionKey, item) => {

        if (actionKey === 'edit') {
            this.setState({
                item: item,
                modalShowEdit: true
            })
        } else if (actionKey === 'enabled') {
            if(item.enabled){
                axios.put(`/auth/users/${item.id}/disable`).then(()=>{
                    //item.enabled = false;
                    console.log(item)
                    console.log(item.enabled);
                })
            }else{
                axios.put(`/auth/users/${item.id}/activate`).then(()=>{
                    //item.enabled = false;
                    console.log(item.enabled);
                })
            }
            this.fetchTableData(1);

        }else if (actionKey==='set'){

            axios.get(`/auth/users/${item.id}/roles`).then( (res)=>{
                let arr=[];
                res.data.map((data)=>{
                    arr.push({
                        key:data.id,
                        title:data.name,
                        description:data.description,
                        disabled:data.disabled,
                        assigned:data.assigned
                    })
                })
                let arrTwo=[];
                arr.map((e)=>{
                    if(e.assigned){
                        arrTwo.push(e.key)
                    }
                })

                this.setState({
                    targetSource:arrTwo,
                    dataSource:arr,
                    modalShowSet: true,
                    rowId:item.id
                })


            })


        }
    }

    tools=(row)=>{
      let icon =  row.enabled ? "unlock " : "lock";
      let title =  row.enabled ? "禁用" : "激活";
      let arr =  [{
          key: 'edit',
          name: '修改',
          color: 'blue',
          icon: 'edit',
      }, {
          key: 'enabled',
          name: title,
          color: 'red',
          icon: icon
      },{
          key: 'set',
          name: '分配',
          color: 'blue',
          icon: 'setting'
      }];
        return arr;

    }


    fields = () => {
        return [{
            label: '姓名',
            type: 'input',
            name: 'realname',
            options: {
                rules: [{
                    required: true,
                    message: '请输入用姓名!',
                }]
            }
        },{
            label: '用户名',
            type: 'input',
            name: 'username',
            options: {
                rules: [{
                    required: true,
                    message: '请输入用户名!',
                }]
            }
        },{
            label: '描述',
            type: 'input',
            name: 'description',
            options: {
                rules: [{
                    required: false,
                    message: '请输入内容!',
                }]
            }
        }]
    }

    fieldsEdit = () => {
        const item = this.state.item;

        return [{
            name: 'id',
            options:{
                initialValue: item.id,
            }
        },{
            label: '账号',
            type: 'input',
            name: 'realname',
            items: item.realname,
            options: {
                initialValue: item.realname,
                rules: [{
                    required: true,
                    message: '请输入账号!',
                }]
            }
        },{
            label: '描述',
            type: 'input',
            name: 'description',
            items: item.description,
            options: {
                initialValue: item.description,
                rules: [{
                    required: true,
                    message: '请输入用户名!',
                }]
            }
        }]
    }

    render() {
        return (
            <div id="wrap">

                <div className="tableBox">
                    <Button onClick={this.add} className="addButton">添加</Button>
                    <div style={{ paddingTop: 43 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            total={this.state.total}
                            pageSize={this.state.pageSize}
                            current={this.state.current}
                            onChange= {this.changePage}
                            pagination={ true }
                            header={ this.tableHeader() }
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={this.tools}
                            scroll={{y: 500 }}
                        />
                    </div>
                </div>
                <FormModal
                    modalKey="add"
                    visible={this.state.modalShow}
                    title="添加用户"
                    fields={this.fields()}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    okText="保存"
                />
                <FormModal
                    modalKey="Edit"
                    visible={this.state.modalShowEdit}
                    title="修改用户"
                    fields={this.fieldsEdit()}
                    onOk={this.onOkEdit}
                    onCancel={this.onCancelEdit}
                    okText="保存"
                />
                <ModelTransfer
                    dataSource={this.state.dataSource}
                    targetSource ={this.state.targetSource}
                    onCanCel={this.onCanCel}
                    modalKey="set"
                    visible={this.state.modalShowSet}
                    title="角色管理"
                    onOkSet={this.onOkSet}
                    onCancel={this.onCancelSet}
                    okText="保存"
                />
            </div>
        )
    }
}